package com.tandashi.springbootstudy01.service;

import com.tandashi.springbootstudy01.component.CommonComponent;
import com.tandashi.springbootstudy01.dto.basic.Agent;
import com.tandashi.springbootstudy01.security.shiro.StudyPrincipal;
import com.tandashi.springbootstudy01.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AgentService {

    public String agentCode() {
        StudyPrincipal principal = commonComponent.getStudyPrincipal();
        if (StringUtils.isNotBlank(principal.getAgentCode())) {
            return principal.getAgentCode();
        }

        if (null == principal.getThirdPartyUser() || StringUtils.isBlank(principal.getThirdPartyUser().getUserId())) {
            if (StringUtils.isNotBlank(principal.getUnionid())) {
                String agentCode = userService.getAgentCodeByUnionId(principal.getUnionid());
                if (StringUtils.isNotBlank(agentCode)) {
                    return agentCode;
                }
            }

            log.warn("no_such_agent:{}", principal);
            throw new RuntimeException("没有查询到代理人信息，请重新登录或稍后重试");
        }

        Agent agent = null;
        try {
            long userId = NumberUtils.toLong(principal.getThirdPartyUser().getUserId());
        } catch (RuntimeException e) {
            log.warn("get_agent_error:" + principal, e);
        }

        if (agent == null || StringUtils.isBlank(agent.getCode())) {
            throw new RuntimeException("用户信息已失效请重新进入");
        }

        principal.setAgentCode(agent.getCode());
        return agent.getCode();

    }

    @Autowired
    private CommonComponent commonComponent;

    @Autowired
    private UserService userService;
}
